import { validate } from "../../utils/validate";
import { API, handleErr } from "../../utils/api";

const studentTypes = ['本科生', '研究生', '博士生'];

const app: any = getApp();

// pages/verify/verify.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    school: '',
    schoolId: '',
    studentType: '',
    studentYear: '',
    password: '',
  },

  async onGo() {
    if (!(
      validate(this.data.name.length, { type: 'number', min: 1, max: 10 }) &&
      validate(this.data.school.length, { type: 'number', min: 1, max: 20 }) &&
      validate(this.data.schoolId.length, { type: 'number', min: 1, max: 20 }) &&
      validate(this.data.studentType.length, { type: 'number', min: 1, max: 10 }) &&
      validate(this.data.studentYear.length, { type: 'number', min: 4, max: 4 })
    )) {
      wx.showToast({
        icon: 'none',
        title: '填写信息不符合要求'
      });
      return;
    }
    wx.showLoading({
      title: '学号密码验证中...'
    });
    if (!(await API.shuVerify(this.data.schoolId, this.data.password))) {
      wx.showToast({
        title: '验证失败',
        icon: 'none'
      });
      return;
    };
    try {
      app.globalData.user = (await API.updateUserInfo({
        name: this.data.name,
        school: this.data.school,
        schoolId: this.data.schoolId,
        studentType: this.data.studentType,
        studentYear: this.data.studentYear,
        shuVerify: this.data.schoolId
      })).data;
      wx.showToast({
        icon: 'success',
        title: '验证成功！',
        complete: () => wx.navigateBack()
      })
    } catch (e) {
      handleErr(e);
    }
  },

  onTypeTap() {
    wx.showActionSheet({
      itemList: studentTypes,
      success: (res) => {
        this.setData({
          studentType: studentTypes[res.tapIndex]
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})